package com.lfg.leetcode.leetcode100;


public class No151reverseWords {

    public static void main(String[] args) {
        String ret = reverseWords("the sky is blue");
        System.out.println(ret);
    }

    public static String reverseWords(String s) {
        if (null == s || s.length() == 0) {
            return s;
        }
        char[] chars = s.toCharArray();
        int endIndex = chars.length - 1;
        for (; endIndex >= 0; endIndex--) {
            if (chars[endIndex] != ' ') {
                break;
            }
        }
        int startIndex = 0;
        for (; startIndex <= endIndex; startIndex++) {
            if (chars[startIndex] != ' ') {
                break;
            }
        }
        exchange(chars, startIndex, endIndex);
        int start = startIndex;
        int end = start;
        int length = 0;
        while (start < endIndex) {
            for (; end <= endIndex; end++) {
                if (chars[end] == ' ') {
                    break;
                }
            }
            exchange(chars, start, end - 1);
            end++;
            start = end;
        }
        StringBuilder sb = new StringBuilder(length);
        for (int i = startIndex; i <= endIndex; i++) {
            if (i < endIndex && chars[i] == ' ' && chars[i + 1] == ' ') {
                continue;
            }
            sb.append(chars[i]);
        }
        return sb.toString();
    }

    private static void exchange(char[] chars, int startIndex, int endIndex) {
        while (startIndex < endIndex) {
            char tmp = chars[startIndex];
            chars[startIndex++] = chars[endIndex];
            chars[endIndex--] = tmp;
        }
    }
}
